<template>
  <van-nav-bar
    title="列表"
    left-text="返回"
    left-arrow
    @click-left="
      () => {
        $router.back('/');
      }
    "
  />
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
    <router-link v-for="item in list" :to="'/detail/'+item.goods_id">
        <van-card
        :price="item.goods_price"
        :title="item.goods_name"
        :thumb="item.goods_big_logo?item.goods_big_logo:'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'"
      />
    </router-link>
      
    </van-list>
  </van-pull-refresh>
</template>

<script setup>
import { ref } from "vue";
import { goodsApi } from "@/api/api";
import { useRoute } from "vue-router";
let route = new useRoute();

let list=ref([])
let page=ref(1)
let pagesize=ref(5)
let total=ref(0)
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);

const goodsData = () => {
  goodsApi(route.params.cat_id).then((res) => {
    console.log("列表数据", res);
    list.value=res.data.message
    let startindex=(page.value-1)*pagesize.value
    let endindex=startindex+pagesize.value
    total.value=res.data.message.goods.length
    list.value=res.data.message.goods.slice(startindex,endindex)
    loading.value=false
    if(list.value.length>=total.value){
        finished.value=true
    }
  });
};
goodsData();

const onRefresh=()=>{
    page.value++
    list.value=[]
    finished.value=false
    refreshing.value=false
    goodsData()
}

const onLoad=async()=>{
    if(finished.value)return
    page.value++
    const res=await goodsApi()
    let startindex=(page.value-1)*pagesize.value
    let endindex=startindex+pagesize.value
    let newData=res.data.message.goods.slice(startindex,endindex)
    list.value=[...list.value,...newData]
    loading.value=false
    if(list.value.length>=total.value){
        finished.value=true
    }
}
</script>

<style lang="scss" scoped></style>
